package com.xb.cloud.usercenter.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.order.service.client.SellOrderMerchantService;
import com.xb.cloud.order.service.client.SellOrderService;
import com.xb.cloud.order.service.client.SellOrderSkuService;
import com.xb.cloud.order.service.client.SoCancelReasonService;
import com.xb.cloud.order.service.client.bo.OrderQueryMerchantBo;
import com.xb.cloud.order.service.client.bo.SoDeliveryBo;
import com.xb.cloud.order.service.client.bo.SoSkuSummeryBo;
import com.xb.cloud.order.service.client.bo.SoSummaryBo;
import com.xb.cloud.order.service.client.model.OrderDeliveryInfo;
import com.xb.cloud.product.merchant.service.client.EndMerchantUserService;
import com.xb.cloud.product.merchant.service.client.ProductSkuService;
import com.xb.cloud.product.merchant.service.client.ShopService;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopBo;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;
import com.xb.cloud.usercenter.client.vo.OrderDetailsVo;
import com.xb.cloud.usercenter.client.vo.OrderMerchantQueryVo;
import com.xb.cloud.usercenter.client.vo.OrderStatisticVo;
import com.xb.cloud.usercenter.client.vo.SellOrderSkuVo;
import com.xb.cloud.usercenter.client.vo.SellOrderVo;
import com.xb.cloud.usercenter.client.vo.UserAddressVo;
import com.xb.cloud.usercenter.config.AppConfig;
import com.xb.cloud.usercenter.service.SellOrderMerchantApiService;

@Service
public class SellOrderMerchantApiServiceImpl implements SellOrderMerchantApiService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SellOrderMerchantApiServiceImpl.class);

	@Resource
	SellOrderMerchantService sellOrderMerchantService;

	@Resource
	SellOrderSkuService sellOrderSkuService;

	@Resource
	SellOrderService sellOrderService;

	@Resource
	SoCancelReasonService soCancelReasonService;

	@Resource
	ShopService shopService;

	@Resource
	private EndMerchantUserService endMerchantUserService;

	@Resource
	private ProductSkuService productSkuService;

	/**
	 * 查询 商家端店铺对应的订单列表
	 */
	@Override
	public RtnInfo getOrderListByStatus(OrderMerchantQueryVo orderQueryVo, Long merchantId) {
		int defaultPageSize = AppConfig.DEFAULT_PAGE_SIZE;

		long companyId = orderQueryVo.getCompanyId();
		int pageNum = orderQueryVo.getPageNum();
		int pageSize = orderQueryVo.getPageSize();
		String status = orderQueryVo.getStatus();

		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(merchantId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				EndMerchantUserBo endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
				orderQueryVo.setShopId(endMerchantUserBo.getShopId());
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		// 当前页默认为1
		pageNum = pageNum < 0 ? 1 : pageNum;
		// 分页大小默认为10
		pageSize = pageSize < defaultPageSize ? defaultPageSize : pageSize;

		OrderQueryMerchantBo orderQueryMerchantBo = new OrderQueryMerchantBo();
		orderQueryMerchantBo.setCompanyId(companyId);
		orderQueryMerchantBo.setShopId(orderQueryVo.getShopId());
		
		try {
			orderQueryMerchantBo.setStatus(Integer.valueOf(status));
		} catch (NumberFormatException e) {
			orderQueryMerchantBo.setStatus(null);
		}
		
		if(orderQueryVo.getStartTime() != null && orderQueryVo.getEndTime() != null) {
			orderQueryMerchantBo.setStartTime(orderQueryVo.getStartTime());
			orderQueryMerchantBo.setEndTime(orderQueryVo.getEndTime());
		}
		
		int count = 0;
		ServiceReturnInfo countReturnInfo = sellOrderMerchantService.countOrderByShopAndStatus(orderQueryMerchantBo);
		if (ServiceReturnUtils.isSuccess(countReturnInfo)) {
			// 是否是成功的
			count = (int) countReturnInfo.getData();
			if (count <= 0) {
				return ReturnUtils.success();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		int maxPageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
		if (pageNum > maxPageNum) {
			return ReturnUtils.error(ReturnCodes.PAGE_NUM_INVALID);
		}

		int startPage = (pageNum - 1) * pageSize;
		orderQueryMerchantBo.setStartPage(startPage < 0 ? 0 : startPage);
		orderQueryMerchantBo.setPageSize(pageSize);

		ServiceReturnInfo orderListReturnInfo = sellOrderMerchantService
				.getOrderListByShopAndStatus(orderQueryMerchantBo);
		List<SoSummaryBo> sellOrderBoList = null;
		if (ServiceReturnUtils.isSuccess(orderListReturnInfo)) {
			// 订单bo列表
			sellOrderBoList = (List<SoSummaryBo>) orderListReturnInfo.getData();
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		List<Long> orderIds = new ArrayList<>();
		for (SoSummaryBo sellOrderBo : sellOrderBoList) {
			Long soId = sellOrderBo.getId();
			orderIds.add(soId);// order item 查询条件
		}

		ShopBo shopBo = null;
		Map<Long, ShopBo> shopMap = new HashMap<>();

		// 查询店铺信息
		ServiceReturnInfo shopBoReturnInfo = shopService.getShopBoById(orderQueryVo.getShopId());
		if (ServiceReturnUtils.isSuccess(shopBoReturnInfo)) {
			// 订单bo列表
			shopBo = (ShopBo) shopBoReturnInfo.getData();
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		// 查询订单对应的sku list
		List<SoSkuSummeryBo> sellOrderSkuList = sellOrderSkuService.getOrderSkuListByOrderIdList(orderIds);
		Map<Long, List<SellOrderSkuVo>> sellOrderSkuMap = new HashMap<>();
		for (SoSkuSummeryBo sellOrderSkuBo : sellOrderSkuList) {
			List<SellOrderSkuVo> items = null;
			SellOrderSkuVo orderSkuVo = new SellOrderSkuVo();
			BeanUtils.copyProperties(sellOrderSkuBo, orderSkuVo);

			Long soId = sellOrderSkuBo.getSoId();
			if (sellOrderSkuMap.get(soId) == null) {
				items = new ArrayList<>();
				items.add(orderSkuVo);
				sellOrderSkuMap.put(soId, items);
			} else {
				items = sellOrderSkuMap.get(soId);
				items.add(orderSkuVo);
			}
		}

		List<SellOrderVo> sellOrderVoList = new ArrayList<>();
		for (SoSummaryBo sellOrderBo : sellOrderBoList) {
			SellOrderVo sellOrderVo = new SellOrderVo();
			Long soId = sellOrderBo.getId();

			// 如果该订单没有sku，界面不显示
			List<SellOrderSkuVo> orderSkuList = sellOrderSkuMap.get(soId);
			if (orderSkuList == null) {
				continue;
			}
			sellOrderVo.setId(soId);
			sellOrderVo.setCreateTime(sellOrderBo.getCreateTime());
			sellOrderVo.setOrderAmount(sellOrderBo.getOrderAmount());
			sellOrderVo.setStatus(sellOrderBo.getStatus());
			sellOrderVo.setBuyPhoneNum(sellOrderBo.getGoodReceiverPhone());
			sellOrderVo.setGoodReceiverName(sellOrderBo.getGoodReceiverName());

			sellOrderVo.setShopName(shopBo.getShopNameCn());
			sellOrderVo.setShopHomeUrl(shopBo.getShopHomeUrl());

			sellOrderVo.setItems(orderSkuList);
			int skuCount = 0;
			for (int i = 0; i < orderSkuList.size(); i++) {
				skuCount = skuCount + orderSkuList.get(i).getSkuNum();
			}
			sellOrderVo.setSkuCount(skuCount);
			sellOrderVoList.add(sellOrderVo);
		}

		return ReturnUtils.success(sellOrderVoList);
	}

	/**
	 * 订单详情 TODO
	 */
	@Override
	public RtnInfo getOrderDetailsById(Long orderId) {

		SoDeliveryBo soDeliveryBo = sellOrderService.getOrderDetailsById(orderId);
		if (soDeliveryBo == null) {
			return ReturnUtils.error(ReturnCodes.ORDER_NOT_EXIST);
		}

		SoSummaryBo soSummaryBo = soDeliveryBo.getSoSummaryBo();
		OrderDeliveryInfo deliveryInfo = soDeliveryBo.getDeliveryInfo();

		List<SoSkuSummeryBo> sellOrderSkuList = sellOrderSkuService.getOrderSkuListByOrderId(orderId);
		ShopBo shopBo = shopService.getById(soSummaryBo.getShopId());

		SellOrderVo sellOrderVo = new SellOrderVo();
		sellOrderVo.setId(orderId);
		sellOrderVo.setStatus(soSummaryBo.getStatus());
		sellOrderVo.setOrderAmount(soSummaryBo.getOrderAmount());
		sellOrderVo.setSkuAmount(soSummaryBo.getSkuAmount());
		sellOrderVo.setCreateTime(soSummaryBo.getCreateTime());
		sellOrderVo.setDeliveryFee(soSummaryBo.getDeliveryFee());
		sellOrderVo.setShopName(shopBo.getShopNameCn());
		sellOrderVo.setShopHomeUrl(shopBo.getShopHomeUrl());
		sellOrderVo.setShopId(shopBo.getId());
		
		sellOrderVo.setBuyPhoneNum(soSummaryBo.getGoodReceiverPhone());
		sellOrderVo.setPaymentConfirmTime(soSummaryBo.getPaymentConfirmTime());
		sellOrderVo.setGoodReceiverName(soSummaryBo.getGoodReceiverName());
		sellOrderVo.setSoUserRemark(soSummaryBo.getSoUserRemark());

		List<SellOrderSkuVo> items = new ArrayList<>();
		for (SoSkuSummeryBo soSkuSummeryBo : sellOrderSkuList) {
			SellOrderSkuVo orderSkuVo = new SellOrderSkuVo();
			BeanUtils.copyProperties(soSkuSummeryBo, orderSkuVo);
			items.add(orderSkuVo);
		}
		sellOrderVo.setItems(items);

		UserAddressVo userAddressVo = new UserAddressVo();
		if (deliveryInfo != null) {
			// userAddressVo.setDetailAddress(deliveryInfo.getGoodReceiverAddress());
			sellOrderVo.setReceiveTime(deliveryInfo.getReceiveTime());
			sellOrderVo.setDeliveryTime(deliveryInfo.getDeliveryTime());
			userAddressVo.setDetailAddress(deliveryInfo.getGoodReceiverAddress());
			userAddressVo.setReceiverName(deliveryInfo.getGoodReceiverName());
			userAddressVo.setPhone(deliveryInfo.getGoodReceiverPhone());
		}

		OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
		orderDetailsVo.setSellOrderVo(sellOrderVo);
		orderDetailsVo.setUserAddressVo(userAddressVo);

		return ReturnUtils.success(orderDetailsVo);
	}

	/**
	 * 订单的数量统计数据
	 */
	@Override
	public RtnInfo getOrderCountWithStatus(OrderMerchantQueryVo orderQueryMerchantVo, Long merchantId) {
		OrderQueryMerchantBo orderQueryMerchantBo = new OrderQueryMerchantBo();

		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(merchantId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				EndMerchantUserBo endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
				orderQueryMerchantVo.setShopId(endMerchantUserBo.getShopId());
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		orderQueryMerchantBo.setCompanyId(orderQueryMerchantVo.getCompanyId());
		orderQueryMerchantBo.setShopId(orderQueryMerchantVo.getShopId());

		try {
			orderQueryMerchantBo.setStatus(Integer.valueOf(orderQueryMerchantVo.getStatus()));
		} catch (NumberFormatException e) {
			orderQueryMerchantBo.setStatus(null);
		}

		// 状态code=订单数量
		ServiceReturnInfo orderCountStatisticRtnInfo = sellOrderMerchantService
				.getOrderCountStatistic(orderQueryMerchantBo);
		if (ServiceReturnUtils.isSuccess(orderCountStatisticRtnInfo)) {
			Map<Integer, Integer> orderCountWithStatus = (Map<Integer, Integer>) orderCountStatisticRtnInfo.getData();
			List<OrderStatisticVo> statisticVos = new ArrayList<OrderStatisticVo>();

			if (orderCountWithStatus != null && !orderCountWithStatus.isEmpty()) {
				for (Integer status : orderCountWithStatus.keySet()) {
					OrderStatisticVo vo = new OrderStatisticVo();
					vo.setCount(orderCountWithStatus.get(status));
					vo.setStatus(status);
					statisticVos.add(vo);
				}
			}
			return ReturnUtils.success(statisticVos);
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

	}

	/**
	 * 确认支付 (商家端)
	 */
	@Override
	public RtnInfo confirmPay(Long orderId, Long merchantId) {

		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(merchantId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		ServiceReturnInfo rtnInfo = sellOrderMerchantService.confirmPay(orderId, endMerchantUserBo);
		if (ServiceReturnUtils.isSuccess(rtnInfo)) {
			return ReturnUtils.success(1);
		} else {
			// TODO 错误类型转换前台错误.
			return ReturnUtils.error(rtnInfo.getCode(), rtnInfo.getMessage(), rtnInfo.getDetailMessage());
		}
	}

	/**
	 * 发货(商家端)
	 */
	public RtnInfo orderDelivery(Long orderId, Long merchantId) {

		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(merchantId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		ServiceReturnInfo rtnInfo = sellOrderMerchantService.orderDelivery(orderId, endMerchantUserBo);
		if (ServiceReturnUtils.isSuccess(rtnInfo)) {
			// 更新销量数据到sku.
			List<SoSkuSummeryBo> sellOrderSkuBoList = (List<SoSkuSummeryBo>) rtnInfo.getData();
			if (sellOrderSkuBoList != null && !sellOrderSkuBoList.isEmpty()) {
				ServiceReturnInfo updateTotalSaleAmountInfo = productSkuService.updateTotalSaleAmout(sellOrderSkuBoList,
						endMerchantUserBo); // 更新销量
				if (ServiceReturnUtils.isSuccess(updateTotalSaleAmountInfo)) {
					return ReturnUtils.success(1);
				} else {
					return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
				}
			}
			return ReturnUtils.success(1);
		} else {
			// TODO 错误类型转换前台错误.
			return ReturnUtils.error(rtnInfo.getCode(), rtnInfo.getMessage(), rtnInfo.getDetailMessage());
		}
	}

	/**
	 * 取消(商家端)
	 */
	public RtnInfo orderCancel(Long orderId, Long merchantId, Long cancelResaonId) {

		EndMerchantUserBo endMerchantUserBo = null;
		// 获取当前merchantId/shopId对应的商家用户
		ServiceReturnInfo merchantReturnInfo = endMerchantUserService.getEndMerchantUserById(merchantId);
		if (ServiceReturnUtils.isSuccess(merchantReturnInfo)) {
			if (merchantReturnInfo.getData() == null) {
				return ReturnUtils.error(ReturnCodes.MERCHANT_NOT_EXIST);
			} else {
				endMerchantUserBo = (EndMerchantUserBo) merchantReturnInfo.getData();
			}
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		ServiceReturnInfo rtnInfo = sellOrderMerchantService.orderCancel(orderId, endMerchantUserBo, cancelResaonId);
		if (ServiceReturnUtils.isSuccess(rtnInfo)) {
			return ReturnUtils.success(1);
		} else {
			// TODO 错误类型转换前台错误.
			return ReturnUtils.error(rtnInfo.getCode(), rtnInfo.getMessage(), rtnInfo.getDetailMessage());
		}
	}

	/**
	 * 获取取消订单的原因的列表
	 */
	@Override
	public RtnInfo getCancelReasonList(Long companyId) {
		ServiceReturnInfo soCancelReasonBoList = soCancelReasonService.getSoCancelReasonBoList(companyId);
		if (ServiceReturnUtils.isSuccess(soCancelReasonBoList)) {
			return ReturnUtils.success(soCancelReasonBoList.getData());
		} else {
			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}
	}

}
